//
//  TopMenusView.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/4/10.
//

import UIKit

class TopMenusView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    private var buttons:Array<UIButton> = []
    private let tip = UIView()
    private let scroll = UIScrollView()
    private let maskLayer = CAGradientLayer()
    private let maskv = UIView()
    private var lastbtn:UIButton?
    var valueChanged:(((String,Int))->Void)?
    private var index = 1
    func nextTab(_ index:Int)  {
        self.updateFrame(buttons[index])
    }
    init(items:Array<(String,Int)>) {
        super.init(frame: CGRect.zero)
        backgroundColor = .white
        scroll.showsHorizontalScrollIndicator = false
        scroll.bounces = false
        addSubview(scroll)
        let moreButton = UIButton()
        addSubview(moreButton)
        var image = UIImage(named: "moremenu")
        image = image?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
        moreButton.tintColor = B999_TITLE_COLOR
        moreButton.setImage(image, for: .normal)
        moreButton.snp.makeConstraints({
            $0.right.equalToSuperview().inset(5)
            $0.centerY.equalToSuperview()
        })
        moreButton.addTarget(self, action: #selector(moreTap), for: .touchUpInside)
        
        
        scroll.snp.makeConstraints({
            $0.left.equalTo(0)
            $0.height.equalToSuperview()
            $0.right.equalTo(moreButton.snp.left).offset(-10)
        })
        
        
        scroll.addSubview(tip)
        scroll.delegate = self

        var temp:UIButton?
        for m in 0..<items.count {
            let n = items[m]
            let l = UIButton(type: .custom)
            l.setTitleColor(RED_COLOR, for: .selected)
            l.setTitle(n.0, for: .normal)
            l.setTitleColor(B000_COLOR, for: .normal)
            l.tag = n.1
            l.titleLabel?.font = Font_Size_16
            scroll.addSubview(l)
            l.snp.makeConstraints({
                if(m == 0){
                    $0.left.equalTo(0)
                }else{
                    $0.left.equalTo((temp?.snp.right)!)
                }
                $0.centerY.equalToSuperview()
                if(m == items.count-1){
                    $0.right.equalToSuperview()
                }
                $0.width.equalTo(50)
                $0.height.equalToSuperview()
            })
            l.addTarget(self, action: #selector(tapclick(_:)), for: .touchUpInside)
            temp = l
            buttons.append(l)
        }
        tip.backgroundColor = RED_COLOR
        
        lastbtn = buttons[index]
        tip.snp.makeConstraints({
            $0.top.equalTo(buttons[index].snp.bottom).inset(2)
            $0.height.equalTo(2)
            $0.centerX.equalTo(buttons[index])
            $0.width.equalTo(buttons[index].snp.width).dividedBy(2)
        })
        lastbtn?.isSelected  = true
        lastbtn?.titleLabel?.font = Font_Size_16
        
        addSubview(maskv)
        maskv.snp.makeConstraints({
            $0.top.bottom.equalTo(moreButton)
            $0.right.equalTo(moreButton.snp.left)
            $0.width.equalTo(20)
        })
        maskLayer.startPoint = CGPoint.init(x: 0, y: 0 )
        maskLayer.endPoint = CGPoint.init(x: 1, y: 0)
        maskLayer.colors = [UIColor.init(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor,UIColor.white.cgColor]
        maskv.layer.addSublayer(maskLayer)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        maskLayer.frame = maskv.bounds
    }
    @objc func tapclick(_ btn:UIButton){
        self.updateFrame(btn)
        self.valueChanged!((btn.currentTitle!,btn.tag))
    }
    private func updateFrame(_ btn:UIButton) {
        self.index = buttons.firstIndex(of: btn)!
        lastbtn?.isSelected = false
        lastbtn?.titleLabel?.font = Font_Size_16
        btn.isSelected = true
        btn.titleLabel?.font = Font_Size_16
        
        tip.snp.remakeConstraints({
            $0.centerX.equalTo(btn)
            $0.width.equalTo(btn.snp.width).dividedBy(2)
            $0.height.equalTo(2)
            $0.top.equalTo(btn.snp.bottom).inset(3)
        })
        UIView.animate(withDuration: 0.5) {
            [weak self] in
            self?.layoutIfNeeded()
        }
        let bx = btn.frame.origin.x
        let bw = btn.frame.size.width
        let w = scroll.frame.width

        if bx + bw/2 > w/2 && bx + bw/2 - w/2 < scroll.contentSize.width - w {
            scroll.setContentOffset(CGPoint.init(x: bx + bw/2 - w/2, y: 0), animated: true)
        }else{
            if(bx + bw/2 - w/2 < scroll.contentSize.width - w){
                scroll.setContentOffset(CGPoint.zero, animated: true)
            }else{
                scroll.setContentOffset(CGPoint.init(x: scroll.contentSize.width-w, y: 0), animated: true)
            }
        }
        lastbtn = btn
    }
    
    @objc func moreTap() {
        let nav = UINavigationController.init(rootViewController: MoreMenusViewController())
        nav.modalPresentationStyle = .overCurrentContext
        nav.modalTransitionStyle = .crossDissolve
        nav.modalPresentationCapturesStatusBarAppearance = true
        self.fatherViewController()?.tabBarController?.present(nav, animated: false, completion: {

        })
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        addBottomBorder()
    }
}
extension TopMenusView:UIGestureRecognizerDelegate{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if((touch.view?.isKind(of: UILabel.self))  == true){
            return false
        }
        return true
    }
}
extension TopMenusView:UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        SystemLog(scroll.contentOffset)
    }
}
